import { Component } from 'react'
import logoSrc from 'assets/logo.png'
import styles from './index.module.scss'
import { Form, Input, Button, Checkbox,Card,message } from 'antd';
import { loginApi } from 'api/user';
import { setToken } from 'utils/storage';

export default class Login extends Component {
  // 提交表单且数据验证成功后回调事件
  handleFinish=async (value) => {
    
    try {
      // console.log('value  ----->  ', value);
      const res = await loginApi(value);
      // console.log('res  ----->  ', res);
      // 3.保存token(要先存 不然鉴权進不來)
      // localStorage.setItem('geek-pc-token',res.data.token)
      setToken(res.data.token)
      // 1.跳转路由
      this.props.history.push('/')
      // 2.用户提示(第个参数二是显示的时间)
      message.success('登录成功',1)
      
    } catch (error) {
      // 4.处理错误逻辑(错误信息要用console.dir打印)
      console.dir('error  ----->  ', error);
      message.error(error.response.data.message)
    }
  }
  render() {
    console.log('styles  ----->  ', styles);
    return (
      <div className={styles['login']}>
        <Card className='login-container'>
          <img src={logoSrc} alt="" className='login-logo'/>
          <Form
            autoComplete="off"
            onFinish={this.handleFinish}
            initialValues={{
              agree: true,
              mobile: '13811111111',
              code: '246810',}}
          >
            {/* FormItem的rules要怕配合name字段使用,否则无效 */}
            <Form.Item name="mobile" rules={[{ required: true, message: '手机号不能为空' },{pattern:/^1[3-9]\d{9}$/,message: '请输入正确的手机号码'}]}>
              <Input placeholder='请输入手机号码'/>
            </Form.Item>

            <Form.Item name="code" rules={[{ required: true, message: '验证码不能为空' },{pattern:/^\d{6}$/,message: '请输入正确的验证码'}]}>
              <Input placeholder='请输入6位验证码'/>
            </Form.Item>

            {/*valuePropName表示使用checked属性值,去验证校验规则  */}
            <Form.Item name="agree" valuePropName="checked" rules={[
                {
                  validator: (_, value) =>{
                    if(value){
                      return Promise.resolve()
                    }else{
                      return Promise.reject('请阅读协议勾选')
                    }
                  }  
                },
              ]}>
              <Checkbox>我已阅读并同意[用户协议]和[隐私条款]</Checkbox>
            </Form.Item>

            <Form.Item>
              <Button type="primary" htmlType="submit" block>
                登录
              </Button>
            </Form.Item>
          </Form>
        </Card>
      </div>
    )
  }
}
